package org.example.server.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.server.bean.PictureBean;
import org.example.server.common.ResultBean;
import org.example.server.service.AccountService;
import org.example.server.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@Slf4j
@RequestMapping("/picture")
public class PictureController {
    @Autowired
    private PictureService pictureService;

    @RequestMapping("/save")
    public ResultBean save(@RequestBody PictureBean pictureBean) {
        try {
            pictureService.save(pictureBean);
            return new ResultBean(200, "保存成功", null);
        } catch (Exception e) {
            log.error("保存图片失败", e);
        }
        return new ResultBean(200, "保存失败", null);
    }
    @PostMapping("/upload")
    public ResultBean upload(@RequestParam("file") MultipartFile file) {
        try {

            System.out.println(file.getOriginalFilename());
            String fileName = file.getOriginalFilename();


            String newName= IdUtil.getSnowflakeNextIdStr()+fileName.substring(fileName.lastIndexOf("."));

            file.transferTo(new File("D:\\upload\\"+newName));
            log.info("上传文件名：" + newName);
            String[] strings ={fileName,newName};
            log.info("上传成功");
            return new ResultBean(200, "上传成功",strings);

        } catch (Exception e) {
            e.getStackTrace();
        }
        return new ResultBean(200, "上传失败", null);
    }
    @RequestMapping("getImage")
    public void getImage(String url, HttpServletResponse response) throws IOException {
        String path = "D:\\upload\\"+url;
        File file=new File(path);
        //跟本地文件路径连接
        FileInputStream fis=new FileInputStream(file);
        //读取文件 这段代码使用了 IoUtil.copy() 方法来复制输入流 (fis) 到输出流 (response.getOutputStream()
        IoUtil.copy(fis,response.getOutputStream());
    }
}
